<template>
    <div class="p-4">
      <!-- 课程选择 -->
      <el-form-item label="选择课程" class="mb-4">
        <el-select v-model="selectedCourseId" placeholder="请选择课程" @change="loadCharts">
          <el-option
            v-for="course in courseOptions"
            :key="course.courseId"
            :label="`${course.courseName}（${course.time} | ${course.classroom}）`"
            :value="course.courseId"
          />
        </el-select>
      </el-form-item>
  
      <!-- 图表展示 -->
      <div class="grid grid-cols-2 gap-4">
        <!-- 成绩等级分布（饼图） -->
        <el-card>
          <div ref="levelChartRef" style="height: 400px;"></div>
        </el-card>
  
        <!-- 平均成绩统计（柱状图） -->
        <el-card>
          <div ref="avgChartRef" style="height: 400px;"></div>
        </el-card>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue'
  import * as echarts from 'echarts'
  import { getScoreAvg, getScoreLevel, getCoursesByTeacherId } from '@/api/score.js'
  import { useUserStore } from '@/stores/user'
  import { ElMessage } from 'element-plus'
  
  const userStore = useUserStore()
  const teacherId = userStore.userInfo.id
  
  const selectedCourseId = ref('')
  const courseOptions = ref([])
  
  const levelChartRef = ref(null)
  const avgChartRef = ref(null)
  
  let levelChart = null
  let avgChart = null
  
  onMounted(() => {
    loadCourses()
  })
  
  function loadCourses() {
    getCoursesByTeacherId(teacherId).then(res => {
      if (res.code === 0) {
        courseOptions.value = res.data || []
        if (courseOptions.value.length > 0) {
          selectedCourseId.value = courseOptions.value[0].courseId
          loadCharts(selectedCourseId.value)
        }
      } else {
        ElMessage.error('课程加载失败')
      }
    })
  }
  
  async function loadCharts(courseId) {
    if (!courseId) return
  
    const [levelRes, avgRes] = await Promise.all([
      getScoreLevel({ courseId }),
      getScoreAvg({ courseId })
    ])
  
    await nextTick() // 保证 DOM 已渲染
  
    // 成绩等级图表
    if (!levelChart) {
      levelChart = echarts.init(levelChartRef.value)
    } else {
      levelChart.clear()
    }
  
    if (levelRes.code === 200 && levelRes.data) {
      const data = levelRes.data
      levelChart.setOption({
        title: { text: '成绩等级分布', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { bottom: '0%' },
        series: [
          {
            name: '等级',
            type: 'pie',
            radius: '50%',
            data: [
              { value: data.Excellent || data.excellent, name: '优秀' },
              { value: data.Good || data.good, name: '良好' },
              { value: data.Pass || data.pass, name: '及格' },
              { value: data.Fail || data.fail, name: '不及格' }
            ]
          }
        ]
      })
    } else {
      ElMessage.warning('成绩等级数据为空')
    }
  
    // 平均成绩图表
    if (!avgChart) {
      avgChart = echarts.init(avgChartRef.value)
    } else {
      avgChart.clear()
    }
  
    if (avgRes.code === 200 && avgRes.data) {
      const data = avgRes.data
      avgChart.setOption({
        title: { text: '平均成绩统计', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: ['平时成绩', '考试成绩', '总成绩']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [
              data.usualScore_avg || 0,
              data.examScore_avg || 0,
              data.totalScore_avg || 0
            ],
            type: 'bar',
            label: {
              show: true,
              position: 'top'
            },
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      })
    } else {
      ElMessage.warning('平均成绩数据为空')
    }
  }
  </script>
  
  <style scoped>
  .el-form-item {
    margin-bottom: 20px;
  }
  </style>
  
  
  